package controllers

import (
	"encoding/json"

	"cashew.com/cashew_common/constants"
	"cashew.com/cashew_task/dtos"
	"github.com/beego/beego/v2/core/logs"
	beego "github.com/beego/beego/v2/server/web"
)

type BaseController struct {
	beego.Controller
	result    *dtos.Response
	RequestId string
}

func (c *BaseController) Prepare() {
	//设置requestId
	c.setRequestId()
}

func (c *BaseController) initResult() {
	c.result, _ = dtos.HttpBuildResponse(constants.HTTP_RESULT_SUCCESS, nil)
	res := c.buildResult(c.result)
	c.Ctx.ResponseWriter.Write(res)
}

func (c *BaseController) buildParamsErrorResult() {
	c.result, _ = dtos.HttpBuildResponse(constants.HTTP_FAIL_PARAMS_ERROR, nil)
	res := c.buildResult(c.result)
	c.Ctx.ResponseWriter.Write(res)
}

func (c *BaseController) buildSystemErrorResult() {
	c.result, _ = dtos.HttpBuildResponse(constants.HTTP_FAIL_SYSTEM_ERROR, nil)
	res := c.buildResult(c.result)
	c.Ctx.ResponseWriter.Write(res)
}

func (c *BaseController) buildResult(result *dtos.Response) []byte {
	res, _ := json.Marshal(result)
	return res
}

func (c *BaseController) setRequestId() {
	//通过请求接口地址和uuid生成requestId
	reqId := c.Ctx.Input.GetData("requestId")
	if reqId != nil {
		c.RequestId = reqId.(string)
	}
}

func (c *BaseController) Error(f interface{}, v ...interface{}) {
	v = append(v, "requestId="+c.RequestId)
	logs.Error(f, v...)
}

func (c *BaseController) Warn(f interface{}, v ...interface{}) {
	v = append(v, "requestId="+c.RequestId)
	logs.Warn(f, v...)
}

func (c *BaseController) Info(f interface{}, v ...interface{}) {
	v = append(v, "requestId="+c.RequestId)
	logs.Info(f, v...)
}

func (c *BaseController) Debug(f interface{}, v ...interface{}) {
	v = append(v, "requestId="+c.RequestId)
	logs.Debug(f, v...)
}
